package com.zy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.dto.LoginFormDTO;
import com.zy.dto.Result;
import com.zy.dto.UserDTO;
import com.zy.entity.User;
import com.zy.mapper.UserMapper;
import com.zy.service.IUserService;
import com.zy.utils.RegexUtils;
import com.zy.utils.SmsTemplate;
import com.zy.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.zy.utils.RedisConstants.*;
import static com.zy.utils.SystemConstants.*;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张宇
 * @since 2024-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     *
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1.校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            // 2.如果不符合,返回错误信息
            return Result.fail("手机号格式错误!");
        }
        // 3.符合,生成验证码
        String code = RandomUtil.randomNumbers(5);
        // 4.保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, Duration.ofMinutes(LOGIN_CODE_TTL));
        // 5.发送验证码
        smsTemplate.sendSms(phone, code, LOGIN_CODE_TTL);
        // 6.返回ok
        return Result.ok();
    }

    /**
     * 登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1.校验手机号
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            // 2.如果不符合,返回错误信息
            return Result.fail("手机号格式错误!");
        }
        // TODO 2.校验验证码,从redis中获取
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        if(code == null || cacheCode == null || !cacheCode.equals(code)){
            // 3.不一致, 返回错误
            return Result.fail("验证码错误!");
        }
        // 4.一致, 手机号查询用户
        User user = query().eq("phone", phone).one();
        // 5.判断用户是否存在
        if(user == null){
            // 6.创建新用户
            user = createUserWithPhone(phone);
        }
        //TODO 7.保存用户信息到redis
        //7.1 随机生成token,作为令牌
        String token = UUID.randomUUID().toString(true);
        // 7.2将user对象作为hash存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //7.3存储
        String tokenKey = LOGIN_USER_KEY +token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //7.4设置token有效期,session指什么都不干30min后过期,token指开始后30min,所以要在拦截器内不停刷新token过期时间
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        //8.返回token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 1.获取日期 2024/1
        String keySuffix = LocalDateTime.now().format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 获取当天是本月第几天
        int dayOfMonth = LocalDateTime.now().getDayOfMonth();
        // 签到
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 1.获取日期 2024/1
        String keySuffix = LocalDateTime.now().format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 获取当天是本月第几天
        int dayOfMonth = LocalDateTime.now().getDayOfMonth();
        // 查询本月的签到次数
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if(result == null || result.isEmpty()){
            // 没有签到记录,返回0
            return Result.ok(0);
        }
        Long num = result.get(0);
        if(num == null || num == 0L){
            // 没有签到记录,返回0
            return Result.ok(0);
        }
        int dateCount = 0;
        // 循环遍历让最后一位与1做与运算
        while (true){
            // 如果是1,代表签到,计数器加1,右移动, 0代表未签到,结束
            if((num & 1) == 0){
                break;
            }
            dateCount++;
            num >>>= 1;
        }

        return Result.ok(dateCount);
    }

    private User createUserWithPhone(String phone) {
        // 1.创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        // 2.保存用户
        save(user);
        return user;
    }
}
